package com.hq.ims.data.event.listener;

import com.hq.ims.data.entity.LogUserLoginInfo;
import com.hq.ims.data.entity.User;
import com.hq.ims.data.event.LogUserLoginInfoEvent;
import com.hq.ims.data.service.BaseUserService;
import com.hq.utils.util.StringUtils;
import com.hq.web.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @description: 用户登录日志监听器
 */
@Component
@Slf4j
public class LogUserLoginInfoListener{

    @Resource
    private BaseUserService baseUserService;


    @Async
    @EventListener
    public void onApplicationEvent(LogUserLoginInfoEvent logUserLoginInfoEvent) {
        //获取传递的事件实体
        LogUserLoginInfo logUserLoginInfo = logUserLoginInfoEvent.getLogUserLoginInfo();

        //补充登录日志字段内容
        logUserLoginInfo.setLoginIp(StringUtils.ifEmptyDefault(logUserLoginInfo.getLoginIp(),"未知ip"));
        logUserLoginInfo.setUserName(StringUtils.ifEmptyDefault(logUserLoginInfo.getUserName(),"未知用户信息"));
        logUserLoginInfo.setCreateUserName(StringUtils.ifEmptyDefault(logUserLoginInfo.getUserName(),"未知用户信息"));
        logUserLoginInfo.setUpdateUserName(StringUtils.ifEmptyDefault(logUserLoginInfo.getUserName(),"未知用户信息"));
        logUserLoginInfo.setUserAccount(StringUtils.ifEmptyDefault(logUserLoginInfo.getUserAccount(),"未知用户信息"));
        logUserLoginInfo.setCompanyId(StringUtils.ifEmptyDefault(logUserLoginInfo.getCompanyId(),"未知公司信息"));
        logUserLoginInfo.setLoginEquipment(logUserLoginInfo.getLoginEquipment() == null ? WebUtils.getDevice() : logUserLoginInfo.getLoginEquipment());
        boolean insertRes = logUserLoginInfo.insert();

        //存储用户最后的登录时间
        baseUserService.lambdaUpdate()
                .eq(User::getId, logUserLoginInfo.getUserId())
                .set(User::getLastLoginDateTime, LocalDateTime.now())
                .set(User::getLastLoginId, logUserLoginInfo.getLogUserLoginInfoId())
                .update();
    }
}
